package com.example.buglydemo.ui

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.example.buglydemo.R
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.crashreport.CrashReport

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initDate()
        initView()
        onClickManagement()
    }

    private fun initDate() {

    }

    private fun initView() {
        findViewById<TextView>(R.id.tv_version_name).text = getVersionName(this)
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    private fun getVersionName(context: Context): String? {
        try {
            val packageManager = context.packageManager
            val packageInfo = packageManager.getPackageInfo(
                    context.packageName, 0)
            return packageInfo.versionName + "   " + packageInfo.versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return null
    }

    private fun onClickManagement() {
        //crash测试
        findViewById<Button>(R.id.btn_bugly_crash).setOnClickListener {
            CrashReport.testJavaCrash()
        }
        //bug测试
        findViewById<Button>(R.id.btn_bug_test).setOnClickListener {
            //Toast.makeText(this, "这是一个bug", Toast.LENGTH_LONG).show()
            Toast.makeText(this, "bug已修复", Toast.LENGTH_LONG).show()
        }
        //检测更新
        findViewById<Button>(R.id.btn_update).setOnClickListener {
            /***** 获取升级信息 *****/
            val upgradeInfo = Beta.getUpgradeInfo()
            if (upgradeInfo != null) {
                //检查更新
                Beta.checkAppUpgrade()
            }else{
                Toast.makeText(this, "当前已是最新版本", Toast.LENGTH_LONG).show()
            }
        }


    }
}